<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

use think\Config;
use think\Validate;//验证
use fast\Random;
use fast\Http;

use app\api\controller\Tpmecms;
use app\api\controller\Pay;



/**
 * 我的
 */
class Me extends Tpmecms
{

    protected $noNeedLogin = ['get_openid','get_user_mobile'];
    protected $noNeedRight = ['*'];

    protected $pros = null;




    // public $uid = '';
    public function _initialize()
    {
        parent::_initialize();
        
        // $this->car_fields = ['model','number','owner','end_time','regtime'];//,'driver_lic','car_type''use_type',

    }

    /**
     * 获取openid
     * @ApiSummary (里面有token，提交接口都要带上)
     * @param string $code
     * @return void
     */
    public function get_openid($code=null){
      
        $app = $this->get_app();
      
        $user = $app->auth->session($code);
        // halt($user);
        if(!empty($user['errcode'])){
            halt($user);
        }
        $openid = $user['openid'];
     
        $data = array();
        $data['openid'] = $openid;
        $user_data = Db::name('user')->where('openid',$openid)->find();
        if($user_data){
            $ret = $this->auth->direct($user_data['id']);
            $data = $this->auth->getUserinfo();
            // $data['uid'] = $user_data['id'];


            // $data['logintime'] = time();
            //开放平台
            if(empty($user_data['unionid']) && (!empty($user['unionid']))){
                Db::name('user')->where('openid',$openid)->update(['unionid'=>$user['unionid']]);
            }
        }else{

            $indata['openid'] = $openid;
            $indata['createtime'] = time();
            $indata['jointime'] = $indata['createtime'];
            $indata['joinip'] = $this->request->ip();
            $indata['logintime'] = time();
            $indata['status'] = 'normal';

            // $indata['stateswitch'] = 1;

            //开放平台
            if(!empty($user['unionid'])){
                $indata['unionid'] = $user['unionid'];
            }
            
     
            $id = Db::name('user')->insertGetId($indata);
            $ret = $this->auth->direct($id);

            $data = $this->auth->getUserinfo();
        }
        
        // $data['is']     = $data['uid'];//未知
        return json($data);
    }





    /**
     * 获取我的优惠券🎫
     *
     * @return void
     */
    public function get_coupons_list()
    {
        $list = Db::name('coupons_user')->where('uid',$this->auth->id)->select();
        $this->success('ok',$list);
    }

    /**
     * 修改小程序用户的昵称和头像
     *
     * @param string $nickname 昵称
     * @param string $img 头像
     * @return void
     */ 
    public function che_user($nickname,$img)
    {   
        $u['id'] = $this->auth->id;
        $data['nickname'] = $nickname;
        $data['avatar'] = $img;
        $res = Db::name('user')->where($u)->update($data);
        if($res){
            $this->success('修改成功');
        }
        $this->success('修改失败');
    }


    /**
     * 获取用户信息
     *
     * @return void
     */
    public function get_user()
    {
        $list['user'] = Db::name('user')->find($this->auth->id);
        $this->success('ok',$list);
    }




    


    /**
     * 小程序授权获取手机号
     *
     * @param string $code
     * @return void
     */    
    public function get_user_mobile($code=null)
    {   
        $app = $this->get_app();
        $data = $this->request->param();
        $user = $app->auth->session($code);
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];

        $session = $user['session_key'];//$app->sns->getSessionKey($code);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);

        //修改手机号
        Db::name('user')->where('openid',$user['openid'])->update(['mobile'=>$decryptedData['phoneNumber']]);
        
        return $decryptedData['phoneNumber'];
        // halt($decryptedData);
        
    }




    /**
     * 获取我的邀请人数
     * @ApiInternal()
     * @param boolean $self 掉接口不需要传
     * @return void
     */
    public function user_get_my_share_num($self=false)
    {
        
        $num = Db::name('user')
                    ->where('pid',$this->auth->id)
                    ->count();
        if($self){
            return $num; 
        }
        $this->success('👌',$num);
        

    }


    /**
     * 修改上级
     * @ApiInternal()
     * @param string $pid 用户id
     * @return void
     */
    public function update_pid($pid)
    {
        
        $user = Db::name('user')->find($this->auth->id);
        if($user){
            if(!empty($user['pid'])){
                $this->error('已经有上级'.$user['pid']);
            }
        }

        
        $res_up = Db::name('user')->where('id',$this->auth->id)->update(['pid'=>$pid]);
        if($res_up){
            $this->success('绑定成功');
        }
    } 

    /**
     * 获取我的邀请列表
     * @ApiInternal()
     * @param integer $page 1
     * @param integer $limit 200
     * @return void
     */
    public function get_share_list($page = 1,$limit = 200)
    {

        $list = Db::name('user')
                    ->where('pid',$this->auth->id)
                    ->order('createtime desc')
                    ->field([ '*,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%m:%s") as date'])
                    ->select();
        $this->success(sizeof($list), $list);
    }


    /**
     * 获取我的分享二维码
     * @ApiInternal()
     * @return void
     */
    public function get_my_share_qr()
    {
        $Qrcode = new Qrcode();
        // $Qrcode->user_get_my_qr();
        return $Qrcode->user_get_my_qr($this->auth->id);
    }




    /**
     * 修改收藏商品
     *
     * @param int $pro_id 商品id
     * @return void
     */
    public function update_gz_pro($pro_id)
    {
       
        $this->verify_pro_id($pro_id);
        // $this->is_uid();
        $data['uid'] = $this->auth->id;
        $data['pro_id'] = $pro_id;
        $res = Db::name('pro_gz')
            ->where($data)
            ->find();  
        
        if($res){
            $del = Db::name('pro_gz')->where($data)->delete();
            if($del){
           
                $this->success('已取消收藏',0);
                // $Dec = Db::name('pro')->where('id',$pro_id)->setDec('gz_num');//收藏数减
            }
        }else{            
            $data['time'] = time();
            $add = Db::name('pro_gz')->insert($data);
            if($add){
           
                $this->success('已收藏',1);
                // $Inc = Db::name('pro')->where('id',$pro_id)->setInc('gz_num');//收藏数加
            }
        }
    
    } 


    /**
     * 获取我收藏的产品列表
     *
     * @param integer $page 1
     * @param integer $limit 9999
     * @return void
     */
    public function get_my_gz_pro_list($page=1,$limit=9999)
    {
        $pro_ids = Db::name('pro_gz')
            ->where('uid',$this->auth->id)
            ->page($page,$limit)
            ->column('pro_id');
        $pro_list = Db::name('pro')->where('id','in',$pro_ids)->select();
        foreach ($pro_list as $key => &$val) {
            $val['specs'] = $this->get_prospecs($val['id']);
        }
        $this->success('ok',$pro_list);
    }


    // /**
    //  * 我已购买列表
    //  * 
    //  * @param integer $page 页码默认1
    //  * @param integer $limit 默认6个
    //  * @return void
    //  */
    // public function get_order_list($page = 1,$limit = 6)
    // {

    //     $list = Db::name('order')
    //         ->where('uid',$this->auth->id)
    //         // ->order('sales desc')
    //         ->page($page,$limit)
    //         ->select();
    //     if($list){

    //         foreach ($list as $key => &$val) {
    //             $val['pro'] = $this->verify_pro_id($val['pro_id']);
    //             // $val['specs'] = $this->get_prospecs($val['id']);
    //         }
    //     }
    //     $this->success('ok',$list);
    // }






}